package ink.metoo.auto.fishpi.chatroom

import com.google.gson.Gson
import com.google.gson.JsonElement
import ink.metoo.auto.fishpi.Log
import ink.metoo.auto.fishpi.Settings
import ink.metoo.auto.fishpi.call.ChatRoomCall
import ink.metoo.auto.fishpi.chatroom.handler.MessageTypeHandler
import ink.metoo.auto.fishpi.chatroom.handler.TypeHandlerFactory
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener

class ChatRoomWebSocketListener : WebSocketListener() {

    private val gson = Gson()

    override fun onOpen(webSocket: WebSocket, response: Response) {
        Log.info("chatroom ${webSocket.request().url} open.")
        val loadHistoryMessage = Settings.chatRoom.loadHistoryMessage
        if (!loadHistoryMessage.enable) {
            return
        }
        ChatRooms.systemConsole(content = "--- 以下为历史消息 ---")
        val page = loadHistoryMessage.page
        (1..page).forEach {
            ChatRoomCall.getMoreMessage(page - it + 1).data.asReversed().forEach { message ->
                MessageTypeHandler.analysisMessage(message, true)
            }
        }
        ChatRooms.systemConsole(content = "--- 以上为历史消息 ---")
    }

    override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
        ChatRooms.cancel()
        Log.info("chatroom ${webSocket.request().url} onClosed. code: $code reason: $reason")
    }

    override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
        Log.info("chatroom ${webSocket.request().url} onClosing. code: $code reason: $reason")
    }

    override fun onMessage(webSocket: WebSocket, text: String) {
        try {
            val isJsonMessage = text.startsWith("{") && text.endsWith("}")
            if (!isJsonMessage) {
                return
            }
            val element = gson.fromJson(text, JsonElement::class.java)
            if (!element.isJsonObject || !element.asJsonObject.has("type")) {
                return
            }
            val message = gson.fromJson(element, Message::class.java)
            TypeHandlerFactory.handle(text, message)
        } catch (e: Throwable) {
            Log.error("chatroom message handler error ${e.message}", e)
        }
    }

    override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
        ChatRooms.cancel()
        Log.error("chatroom webSocket fail", t)
    }


}